package filter;

import hib.Surl;
import hib.SurlDAO;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import servlet.ChangeIdToInfo;

public class IndexFilter extends HttpServlet implements Filter{
	public   void   init(FilterConfig   filterConfig)   throws   ServletException   {  
    }  
 
    public   void   doFilter(ServletRequest   request,   ServletResponse   response,  
                                              FilterChain   chain)   throws   IOException,   ServletException   {  
        HttpServletRequest   req   =   (HttpServletRequest)   request;  
        HttpServletResponse   res   =   (HttpServletResponse)   response;  
        ChangeIdToInfo to=new ChangeIdToInfo();
        SurlDAO dao=new SurlDAO();
        Surl url=null;
 
       
      if(!req.getServletPath().isEmpty()&&!"/CreateShortUrlServ".equals(req.getServletPath())&&!"/404.html".equals(req.getServletPath())&&!"/index.jsp".equals(req.getServletPath()))
      {
    	  String temp=req.getServletPath().substring(1);
    	  int id=to.toBeLong(temp);
    	
    	  url=dao.findById(id);
    	  if(url!=null)
    		  res.sendRedirect(url.getUrl());
    	  else
    		  res.sendRedirect("404.html");
      }else
           chain.doFilter(request,response);  
    }  
 
    public   void   destroy()   {  
    }  
}
